package com.ruoyi.ai.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.ai.api.OpenAiApi;
import com.ruoyi.ai.core.config.openai.DouBaoAiPropertyConfig;
import com.ruoyi.ai.domain.MessageParamReqBody;
import com.ruoyi.ai.domain.MessageParamResBody;
import com.ruoyi.ai.service.HttpClientService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.HttpClientErrorException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 豆包模型ai接口
 *
 * @author xudm
 */
@Component
public class DouBaoAiApi implements OpenAiApi {

    @Resource
    private HttpClientService httpClientService;

    @Resource
    private DouBaoAiPropertyConfig douBaoAiPropertyConfig;

    @Override
    public String getAnswer(String question) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer " + douBaoAiPropertyConfig.getApiKey());

        try {
            // 发送 POST 请求
            MessageParamReqBody messageParamReqBody = new MessageParamReqBody();
            messageParamReqBody.setModel(douBaoAiPropertyConfig.getModel());
            messageParamReqBody.setMax_tokens(4096);
            messageParamReqBody.setTemperature(douBaoAiPropertyConfig.getTemperature());
            messageParamReqBody.setStream(false);

            MessageParamReqBody.MessageParam system = new MessageParamReqBody.MessageParam();
            system.setRole("system");
            system.setContent("你是豆包，是由字节跳动开发的 AI 人工智能助手.");

            MessageParamReqBody.MessageParam user = new MessageParamReqBody.MessageParam();
            user.setRole("user");
            user.setContent(question);

            messageParamReqBody.setMessages(List.of(system, user));

            String sendPostRequest = httpClientService.sendPostRequest(douBaoAiPropertyConfig.getApiUrl(), JSON.toJSONString(messageParamReqBody), headers);

            MessageParamResBody body = JSON.parseObject(sendPostRequest, MessageParamResBody.class);
            String content = body.getChoices().get(0).getMessage().getContent();
            Assert.notNull(content, "content is null");
            return content;
        } catch (HttpClientErrorException e) {
            // 处理客户端错误
            return "Client error: " + e.getMessage();
        } catch (Exception e) {
            // 处理其他异常
            return "Error: " + e.getMessage();
        }
    }

}
